package com.suyang.syt.service.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.dao.interfaces.WeixinGroupDao;
import com.suyang.syt.dao.interfaces.WeixinMenuDao;
import com.suyang.syt.dao.interfaces.WeixinMsgImageTextDao;
import com.suyang.syt.dao.interfaces.WeixinMsgReceiveDao;
import com.suyang.syt.dao.interfaces.WeixinMsgReplyDao;
import com.suyang.syt.dao.interfaces.WeixinQRcodeDao;
import com.suyang.syt.dao.interfaces.WeixinUserDao;
import com.suyang.syt.model.WeixinGroup;
import com.suyang.syt.model.WeixinMenu;
import com.suyang.syt.model.WeixinMsgImageText;
import com.suyang.syt.model.WeixinMsgReceive;
import com.suyang.syt.model.WeixinMsgReply;
import com.suyang.syt.model.WeixinQRcode;
import com.suyang.syt.model.WeixinUser;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.service.interfaces.WeixinMsgReplyService;
import com.suyang.syt.util.DateFormat;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.HttpTookit;
import com.suyang.syt.weixin.WeixinKit;

@Service
public class WeixinMsgReplyServiceImpl implements WeixinMsgReplyService {

	private Logger logger = Logger.getLogger(WeixinMsgReplyServiceImpl.class);

	@Autowired
	private WeixinMsgReceiveDao weixinMsgReceiveDao;
	@Autowired
	private WeixinMsgReplyDao weixinMsgReplyDao;
	@Autowired
	private WeixinMsgImageTextDao weixinMsgImageTextDao;
	@Autowired
	private WeixinMenuDao weixinMenuDao;
	@Autowired
	private WeixinUserDao weixinUserDao;
	@Autowired
	private WeixinGroupDao weixinGroupDao;
	@Autowired
	private WeixinQRcodeDao weixinQRcodeDao;

	@Override
	public String addReplyMsg(WeixinMsgReceive receiveMsg) throws Exception {
		if (receiveMsg != null) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("ToUserName", receiveMsg.getFromUserName());
			map.put("FromUserName", receiveMsg.getToUserName());
			map.put("CreateTime", String.valueOf(System.currentTimeMillis()));
			if (WeixinKit.MSG_TEXT.equals(receiveMsg.getMsgType())) {
				// 文本消息类型
				map = doSendMsg(map, receiveMsg.getContent(), 0);
			} else if (WeixinKit.MSG_IMAGE.equals(receiveMsg.getMsgType())) {
				// 图片消息类型
				// 根据receiveMsg的picUrl地址获取图片,将图片保存到项目资源路径下
				String fileName = System.currentTimeMillis() + ".jpg";
				File file = new File(BeanFactoryContext.getRealPath() + "/resources/upload/weixin/" + fileName);
				HttpTookit.doGet(receiveMsg.getPicUrl(), null, "UTF-8", file);
				receiveMsg.setUploadPicName(fileName);
				weixinMsgReceiveDao.updatePicName(receiveMsg.getId(), fileName);
				map.put("MsgType", WeixinKit.MSG_IMAGE);
				map.put("Image", "<MediaId>" + receiveMsg.getMediaId() + "</MediaId>");
			} else if (WeixinKit.MSG_VOICE.equals(receiveMsg.getMsgType())) {
				// 语音消息类型
				logger.info("发送的语音:" + receiveMsg.getMediaId());
				return null;
			} else if (WeixinKit.MSG_VIDEO.equals(receiveMsg.getMsgType())) {
				// 视频消息类型
				logger.info("发送的视频:" + receiveMsg.getMediaId());
				return null;
			} else if (WeixinKit.MSG_SHORTVIDEO.equals(receiveMsg.getMsgType())) {
				// 小视频消息类型
				logger.info("发送的小视频:" + receiveMsg.getMediaId());
				return null;
			} else if (WeixinKit.MSG_LOCATION.equals(receiveMsg.getMsgType())) {
				// 地理位置消息类型
				logger.info("发送的位置:" + receiveMsg.getLabel());
				return null;
			} else if (WeixinKit.MSG_LINK.equals(receiveMsg.getMsgType())) {
				// 链接消息类型
				logger.info("发送的链接:" + receiveMsg.getTitle());
				return null;
			} else if (WeixinKit.MSG_EVENT.equals(receiveMsg.getMsgType())) {
				// 事件消息类型
				if (WeixinKit.EVENT_SUBSCRIBE.equals(receiveMsg.getEvent())) {
					// 用户在关注公众号时
					WeixinUser weixinUser = weixinUserDao.loadByOpenid(receiveMsg.getFromUserName());
					String content = "";
					if (EmptyUtil.isNotEmpty(weixinUser)) {
						content = "欢迎您再次关注童趣堂!";
					} else {
						content = "欢迎关注童趣堂,请前往绑定平台账号以获得更好的服务!";
					}
					map.put("MsgType", WeixinKit.MSG_TEXT);
					map.put("Content", content);
					logger.info("用户已经订阅,用户ID:" + receiveMsg.getFromUserName());
					weixinUserDao.updateAuthorize(receiveMsg.getFromUserName());
					HandleScanQrcode(weixinUser.getStatus(), true, receiveMsg.getEventKey(), receiveMsg.getFromUserName(), map);
				} else if (WeixinKit.EVENT_UNSUBSCRIBE.equals(receiveMsg.getEvent())) {
					// 用户在取消关注公众号时
					WeixinUser weixinUser = weixinUserDao.loadByOpenid(receiveMsg.getFromUserName());
					if (EmptyUtil.isNotEmpty(weixinUser)) {
						weixinUser.setSubscribe(0);
						weixinUser.setSubscribe_time(DateFormat.dateToString(new Date()));
						weixinUserDao.update(weixinUser);
					}
					logger.info("用户已经取消订阅,用户ID:" + receiveMsg.getFromUserName());
					return null;
				} else if (WeixinKit.EVENT_SCAN.equals(receiveMsg.getEvent())) {
					// 用户已关注时的事件推送
					WeixinUser weixinUser = weixinUserDao.loadByOpenid(receiveMsg.getFromUserName());
					String content = "";
					if (EmptyUtil.isNotEmpty(weixinUser)) {
						content = "欢迎您再次关注童趣堂!";
					} else {
						content = "欢迎关注童趣堂,请前往绑定平台账号以获得更好的服务!";
					}
					map.put("MsgType", WeixinKit.MSG_TEXT);
					map.put("Content", content);
					logger.info("用户已经订阅,用户ID:" + receiveMsg.getFromUserName());
					weixinUserDao.updateAuthorize(receiveMsg.getFromUserName());
					HandleScanQrcode(weixinUser.getStatus(), false, receiveMsg.getEventKey(), receiveMsg.getFromUserName(), map);
				} else if (WeixinKit.EVENT_LOCATION.equals(receiveMsg.getEvent())) {
					// 上报地理位置事件
					return null;
				} else if (WeixinKit.EVENT_CLICK.equals(receiveMsg.getEvent())) {
					// 点击菜单拉取消息时的事件推送
					WeixinMenu weixinMenu = weixinMenuDao.getByKey(receiveMsg.getEventKey());
					if (weixinMenu != null) {
						map = doSendMsg(map, null, weixinMenu.getMsgReplyId());
					}
				} else if (WeixinKit.EVENT_VIEW.equals(receiveMsg.getEvent())) {
					// 点击菜单跳转链接时的事件推送
					return null;
				} else if (WeixinKit.EVENT_SCANCODE_PUSH.equals(receiveMsg.getEvent())) {
					// 扫码推事件的事件推送
					return null;
				} else if (WeixinKit.EVENT_SCANCODE_WAITMSG.equals(receiveMsg.getEvent())) {
					// 扫码推事件且弹出“消息接收中”提示框的事件推送
					map.put("MsgType", WeixinKit.MSG_TEXT);
					map.put("Content", "您扫描的类型为:" + receiveMsg.getScanType() + ",内容为:" + receiveMsg.getScanResult());
				} else if (WeixinKit.EVENT_PIC_SYSPHOTO.equals(receiveMsg.getEvent()) || WeixinKit.EVENT_PIC_PHOTO_OR_ALBUM.equals(receiveMsg.getEvent()) || WeixinKit.EVENT_PIC_WEIXIN.equals(receiveMsg.getEvent())) {
					// 弹出拍照或者相册发图的事件推送
					logger.info("发图的数量为:" + receiveMsg.getCount() + ",内容为:" + receiveMsg.getPicMd5Sum());
					return null;
				} else if (WeixinKit.EVENT_LOCATION_SELECT.equals(receiveMsg.getEvent())) {
					// 弹出地理位置选择器的事件推送
					logger.info("您的地理位置为:" + receiveMsg.getLabel());
					return null;
				}
			}
			return WeixinKit.createXML(map);
		}
		return null;
	}

	/** 根据用户输入的文本内容进行处理程序 */
	private Map<String, String> doSendMsg(Map<String, String> map, String sendMsg, long msgReplyId) {
		WeixinMsgReply weixinReplyMsg = null;
		if (EmptyUtil.isNotEmpty(sendMsg)) {
			weixinReplyMsg = weixinMsgReplyDao.getReplyMsg(sendMsg);
		} else {
			weixinReplyMsg = weixinMsgReplyDao.load(msgReplyId);
		}
		if (weixinReplyMsg != null) {
			String type = weixinReplyMsg.getMsgType();
			map.put("MsgType", type);
			if (WeixinKit.MSG_TEXT.equals(type)) {
				// 回复的类型为文本
				map.put("Content", weixinReplyMsg.getContent());
			} else if (WeixinKit.MSG_IMAGE.equals(type)) {
				// 回复的类型为图片
				StringBuilder sb = new StringBuilder();
				sb.append("<MediaId>").append(weixinReplyMsg.getMediaId()).append("</MediaId>");
				map.put("Image", sb.toString());
			} else if (WeixinKit.MSG_VOICE.equals(type)) {
				// 回复的语音
				StringBuilder sb = new StringBuilder();
				sb.append("<MediaId>").append(weixinReplyMsg.getMediaId()).append("</MediaId>");
				map.put("Voice", sb.toString());
			} else if (WeixinKit.MSG_VIDEO.equals(type)) {
				// 回复的视频
				StringBuilder sb = new StringBuilder();
				sb.append("<MediaId>").append(weixinReplyMsg.getMediaId()).append("</MediaId>");
				sb.append("<Title>").append(weixinReplyMsg.getTitle()).append("</Title>");
				sb.append("<Description>").append(weixinReplyMsg.getDescription()).append("</Description>");
				map.put("Video", sb.toString());
			} else if (WeixinKit.MSG_MUSIC.equals(type)) {
				// 回复的音乐
				StringBuilder sb = new StringBuilder();
				sb.append("<Title>").append(weixinReplyMsg.getTitle()).append("</Title>");
				sb.append("<Description>").append(weixinReplyMsg.getDescription()).append("</Description>");
				sb.append("<MusicUrl>").append(weixinReplyMsg.getMusicUrl()).append("</MusicUrl>");
				sb.append("<HQMusicUrl>").append(weixinReplyMsg.getHqMusicUrl()).append("</HQMusicUrl>");
				sb.append("<ThumbMediaId>").append(weixinReplyMsg.getThumbMediaId()).append("</ThumbMediaId>");
				map.put("Music", sb.toString());
			} else if (WeixinKit.MSG_NEWS.equals(type)) {
				// 回复的图文信息
				List<WeixinMsgImageText> list = weixinMsgImageTextDao.listInIds(weixinReplyMsg.getWeixinImageTextIds());
				int size = list.size();
				if (EmptyUtil.isNotEmpty(list)) {
					// 图文信息不能超过10条
					if (size > 10) {
						size = 10;
					}
					StringBuilder sb = new StringBuilder();
					for (WeixinMsgImageText witm : list) {
						sb.append("<item>");
						sb.append("<Title>").append(witm.getTitle()).append("</Title>");
						sb.append("<Description>").append(witm.getDescription()).append("</Description>");
						sb.append("<PicUrl>").append(witm.getPicUrl()).append("</PicUrl>");
						sb.append("<Url>").append(witm.getUrl()).append("</Url>");
						sb.append("</item>");
					}
					map.put("ArticleCount", size + "");
					map.put("Articles", sb.toString());
				}
			}
		} else {
			// 转发到多客服系统
			map.put("MsgType", "transfer_customer_service");
		}
		return map;
	}

	/** 处理扫码事件 */
	private void HandleScanQrcode(int bindingStatus, boolean isSubscribe, String eventKey, String openid, Map<String, String> map) {
		if (EmptyUtil.isNotEmpty(eventKey)) {
			if (isSubscribe) {
				WeixinQRcode weixinQRcode = weixinQRcodeDao.loadByScene(eventKey.split("_")[1]);
				if (weixinQRcode != null && weixinQRcode.getStatus() == 3) {
					// 扫描的是移动用户到特定组的二维码
					HandleScanQrcodeStatus3(weixinQRcode.getQrdata(), openid);
				}
			} else {
				WeixinQRcode weixinQRcode = weixinQRcodeDao.loadByScene(eventKey);
				if (weixinQRcode != null) {
					int status = weixinQRcode.getStatus();
					switch (status) {
					case 1:
						// 微信扫码登陆
						if (bindingStatus != 1) {
							// 用户没有绑定
							map.put("Content", "对不起,您没有绑定用户,请先绑定用户!");
						} else {
							if (weixinQRcode.getTimestamp() + weixinQRcode.getExpire_seconds() * 1000 > System.currentTimeMillis()) {
								// 临时二维码没有超时
								weixinQRcode.setQrdata(openid);
								weixinQRcodeDao.update(weixinQRcode);
								map.put("Content", "您好,您已经通过微信授权,请稍后!");
							} else {
								map.put("Content", "您好,您扫描的二维码已经过期,请重新刷新页面进行扫码!");
							}
						}
						break;
					case 2:
						// 微信扫码改密码
						if (bindingStatus != 1) {
							// 用户没有绑定
							map.put("Content", "对不起,您没有绑定用户,请先绑定用户!");
						} else {
							if (weixinQRcode.getTimestamp() + weixinQRcode.getExpire_seconds() * 1000 > System.currentTimeMillis()) {
								// 临时二维码没有超时
								map.put("Content", "您好,您已经通过微信授权,可以进行修改童趣堂的后台密码,修改密码请点击:" + weixinQRcode.getQrdata());
							} else {
								map.put("Content", "您好,您扫描的二维码已经过期,请重新刷新页面进行扫码!");
							}
						}
						break;
					case 3:
						// 微信扫码移动用户到特定组
						HandleScanQrcodeStatus3(weixinQRcode.getQrdata(), openid);
						break;
					case 4:
						// 微信扫码账号绑定
						map.put("Content", "您好,欢迎您前往绑定平台账号以获取更好的用户体验:" + weixinQRcode.getQrdata());
						break;
					}
				}
			}
		}
	}

	/** 处理微信扫码移动用户到特定组的事件,对应status为3 */
	private void HandleScanQrcodeStatus3(String qrdata, String openid) {
		int to_groupid = Integer.parseInt(qrdata);
		if (WeixinKit.updateBatchmoveGroup(openid, to_groupid)) {
			WeixinGroup weixinGroup = weixinGroupDao.loadByid(to_groupid);
			if (weixinGroup != null) {
				weixinUserDao.updateBatchmoveGroup(openid, weixinGroup.getId(), weixinGroup.getName());
				logger.info("用户已经转移到了" + weixinGroup.getName() + "分组中,用户ID:" + openid);
			}
		}
	}

	@Override
	public AjaxObj add(WeixinMsgReply weixinMsgReply) throws Exception {
		AjaxObj ajaxObj = validate(weixinMsgReply);
		if (ajaxObj != null && ajaxObj.getResult() == 1) {
			weixinMsgReplyDao.add(weixinMsgReply);
			return ajaxObj;
		} else {
			return ajaxObj;
		}
	}

	private AjaxObj validate(WeixinMsgReply weixinMsgReply) {
		if (weixinMsgReply == null) {
			return new AjaxObj(0, "回复消息出错,请联系管理员!");
		}
		String type = weixinMsgReply.getMsgType();
		if (EmptyUtil.isEmpty(weixinMsgReply.getSendMsg()) || EmptyUtil.isEmpty(type)) {
			return new AjaxObj(0, "接收消息或消息类型不能为空!");
		}
		if (WeixinKit.MSG_TEXT.equals(type)) {
			if (EmptyUtil.isEmpty(weixinMsgReply.getContent())) {
				return new AjaxObj(0, "文本消息类型中文本内容不能为空!");
			}
		} else if (WeixinKit.MSG_IMAGE.equals(type)) {
			if (EmptyUtil.isEmpty(weixinMsgReply.getMediaId())) {
				return new AjaxObj(0, "图片消息类型中素材不能为空!");
			}
		} else if (WeixinKit.MSG_VOICE.equals(type)) {
			if (EmptyUtil.isEmpty(weixinMsgReply.getMediaId())) {
				return new AjaxObj(0, "语音消息类型中素材不能为空!");
			}
		} else if (WeixinKit.MSG_VIDEO.equals(type)) {
			if (EmptyUtil.isEmpty(weixinMsgReply.getMediaId())) {
				return new AjaxObj(0, "视频消息类型中素材不能为空!");
			}
			if (EmptyUtil.isEmpty(weixinMsgReply.getTitle())) {
				return new AjaxObj(0, "视频消息类型中标题不能为空!");
			}
			if (EmptyUtil.isEmpty(weixinMsgReply.getDescription())) {
				return new AjaxObj(0, "视频消息类型中描述不能为空!");
			}
		} else if (WeixinKit.MSG_MUSIC.equals(type)) {
			if (EmptyUtil.isEmpty(weixinMsgReply.getTitle())) {
				return new AjaxObj(0, "音乐消息类型中标题不能为空!");
			}
			if (EmptyUtil.isEmpty(weixinMsgReply.getDescription())) {
				return new AjaxObj(0, "音乐消息类型中描述不能为空!");
			}
			if (EmptyUtil.isEmpty(weixinMsgReply.getMusicUrl())) {
				return new AjaxObj(0, "音乐消息类型中音乐链接不能为空!");
			}
			if (EmptyUtil.isEmpty(weixinMsgReply.getHqMusicUrl())) {
				return new AjaxObj(0, "音乐消息类型中高质量音乐链接不能为空!");
			}
			if (EmptyUtil.isEmpty(weixinMsgReply.getThumbMediaId())) {
				return new AjaxObj(0, "音乐消息类型中缩略图不能为空!");
			}
		}
		return new AjaxObj(1, "成功");
	}

	@Override
	public PagerEasyUI<WeixinMsgReply> listByEasyUI(int page, int rows, String sort, String order, String createDate1, String createDate2) throws Exception {
		StringBuilder hql = new StringBuilder(" from WeixinMsgReply wrm where 1=1 ");
		if (EmptyUtil.isNotEmpty(createDate1)) {
			hql.append(" and wrm.createTime >= '").append(createDate1).append("' ");
		}
		if (EmptyUtil.isNotEmpty(createDate2)) {
			hql.append(" and wrm.createTime <= '").append(createDate2).append("' ");
		}
		if (EmptyUtil.isNotEmpty(sort)) {
			hql.append(" order by wrm.").append(sort);
		}
		if (EmptyUtil.isNotEmpty(order)) {
			hql.append(" ").append(order);
		}
		PagerEasyUI<WeixinMsgReply> easyUIPager = new PagerEasyUI<WeixinMsgReply>();
		List<WeixinMsgReply> list = weixinMsgReplyDao.findByEasyUI(hql.toString(), page, rows);
		if (EmptyUtil.isNotEmpty(list)) {
			easyUIPager.setRows(list);
			easyUIPager.setTotal((Long) weixinMsgReplyDao.queryByHql(" select count(*) " + hql.substring(0, hql.indexOf("order by"))));
		}
		return easyUIPager;
	}

	@Override
	public AjaxObj deletes(String ids) throws Exception {
		if (EmptyUtil.isNotEmpty(ids)) {
			weixinMsgReplyDao.deletes(ids);
			return new AjaxObj(1, "删除成功！");
		} else {
			return new AjaxObj(0, "请选择要删除的记录！");
		}
	}

}
